package com.example.demo.config;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author: wukangrong
 * @date: 2020/12/25 15:24
 * @description:
 */
@Component
public class JedisLock {

    @Resource(name = "customStringRedisTemplate")
    private StringRedisTemplate stringRedisTemplate;

    public boolean lock(String id) {
        for (; ; ) {
            boolean res = stringRedisTemplate.opsForValue().setIfAbsent("test-key", id, 5, TimeUnit.SECONDS);
            if (res) {
                return true;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
    public boolean unlock(String id) {
        String val = stringRedisTemplate.opsForValue().get("test-key");
        if (id.equals(val)) {
            return stringRedisTemplate.delete("test-key");
        }
        return false;
    }
}
